管理设计篇之"网关模式" [2026重制版]
核心变更说明:本文基于原本文档第56篇重写,全面更新至2026年技术栈。新增 Kong 3.7、Apache APISIX 3.9、Envoy Gateway v1.1、KrakenD 深度对比,补充云原生网关架构设计、性能基准测试(来源:各项目官方 Benchmark)、完整的生产级部署配置。
一、问题背景:为什么需要 API 网关
1.1 从单体到微服务的入口挑战
在微服务架构中,客户端(Web/移动端/IoT)不再直接与单一后端通信,而是需要面对数十甚至数百个微服务。这带来了以下核心问题:
图表渲染中…
1.2 API 网关的核心价值
API 网关是系统的统一入口,类似于面向对象中的 Facade 模式——封装内部系统复杂性,对外提供简洁的 API。
图表渲染中…
二、主流 API 网关方案对比
2.1 方案全景图
图表渲染中…
2.2 核心指标对比表
| 特性 | Kong 3.7 | Apache APISIX 3.9 | Envoy Gateway v1.1 | Nginx Plus | Tyk |
|---|---|---|---|---|---|
| 开发语言 | Lua (OpenResty) | Lua + Rust | Go | C | Go |
| 底层引擎 | Nginx/OpenResty | Nginx/APISIX | Envoy Proxy | Nginx | Go net/http |
| 最大 QPS | ~80k | ~100k | ~150k | ~200k | ~50k |
| P99 延迟 | ~2ms | ~1.5ms | ~1ms | ~0.8ms | ~3ms |
| 插件数量 | 300+ | 80+ 内置 | 中等(扩展中) | 模块化 | 30+ |
| 动态配置 | ✅ Admin API + DB | ✅ etcd | ✅ xDS/K8s CRD | ⚠️ reload | ✅ Dashboard |
| K8s 原生 | ⚠️ Ingress Controller | ✅ CRD 原生 | ✅ 原生支持 | ✅ Ingress | ✅ Operator |
| 社区活跃度 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ |
| GitHub Stars | ~37k | ~13k | ~2k (快速增长) | - | ~9k |
| 商业公司 | Kong Inc. | Apache 基金会 | CNCF | F5 Networks | Tyk Technologies |
| 许可证 | Apache 2.0 | Apache 2.0 | Apache 2.0 | 商业许可 | MPL 2.0/Mozilla |
| 适合场景 | 企业级全功能 | 云原生高性能 | K8s/Gateway API | 传统部署 | API 管理 |
数据来源:各项目官方文档及 TechEmpower Benchmark
三、Kong 网关深度实践
3.1 架构概览
Kong 是目前全球最流行的开源 API 网关,基于 OpenResty (Nginx + LuaJIT) 构建。
图表渲染中…
3.2 Docker Compose 快速部署
yaml
# docker-compose-kong.yml
version: '3.8'
networks:
kong-net:
driver: bridge
services:
# PostgreSQL 数据库
kong-database:
image: postgres:16-alpine
container_name: kong-db
environment:
POSTGRES_USER: kong
POSTGRES_DB: kong
POSTGRES_PASSWORD: ${KONG_PG_PASSWORD:-kong_password}
ports:
- "15432:5432"
networks:
- kong-net
healthcheck:
test: ["CMD-SHELL", "pg_isready -U kong -d kong"]
interval: 10s
timeout: 5s
retries: 5
# Kong 迁移初始化
kong-migration:
image: kong:3.7.0-ubuntu
container_name: kong-migration
depends_on:
kong-database:
condition: service_healthy
environment:
KONG_DATABASE: postgres
KONG_PG_HOST: kong-database
KONG_PG_USER: kong
KONG_PG_PASSWORD: ${KONG_PG_PASSWORD:-kong_password}
KONG_CASSANDRA_CONTACT_POINTS: kong-database
command: kong migrations bootstrap
networks:
- kong-net
restart on-failure
# Kong 网关节点
kong-gateway:
image: kong:3.7.0-ubuntu
container_name: kong-gateway
depends_on:
kong-migration:
condition: service_completed_successfully
environment:
KONG_DATABASE: postgres
KONG_PG_HOST: kong-database
KONG_PG_USER: kong
KONG_PG_PASSWORD: ${KONG_PG_PASSWORD:-kong_password}
KONG_PROXY_ACCESS_LOG: /dev/stdout
KONG_ADMIN_ACCESS_LOG: /dev/stdout
KONG_PROXY_ERROR_LOG: /dev/stderr
KONG_ADMIN_ERROR_LOG: /dev/stderr
KONG_ADMIN_LISTEN: 0.0.0.0:8001
KONG_ADMIN_GUI_URL: http://localhost:8002
# 关键插件配置
KONG_PLUGINS: bundled,cors,key-auth,rate-limiting,jwt,oauth2,proxy-cache,request-transformer,response-transformer,acl,ip-restriction
KONG_NGINX_PROXY_REAL_IP_RECURSIVE: "on"
KONG_TRUSTED_PROXIES: 0.0.0.0/0,::/0
ports:
- "8000:8000" # Proxy 端口 (HTTP)
- "8443:8443" # Proxy 端口 (HTTPS)
- "8001:8001" # Admin API 端口
- "8444:8444" # Admin API HTTPS
- "8002:8002" # Manager GUI
networks:
- kong-net
healthcheck:
test: ["CMD", "kong", "health"]
interval: 10s
timeout: 5s
retries: 5
# Kong Manager GUI (可选)
kong-manager:
image: kong:3.7.0-ubuntu
container_name: kong-manager
depends_on:
kong-gateway:
condition: service_healthy
environment:
KONG_ADMIN_LISTEN: 0.0.0.0:8002
KONG_ADMIN_GUI_URL: http://localhost:8002
KONG_DATABASE: off
KONG_DECLARATIVE_CONFIG: ""
ports:
- "8002:8002"
networks:
- kong-net3.3 核心配置示例
创建 Service 和 Route
bash
# ====== 1. 创建上游服务 ======
# 用户服务
curl -i -X POST http://localhost:8001/services \
--data name=user-service \
--data url=http://user-service:8081 \
--data connect_timeout=5000 \
--data write_timeout=5000 \
--data read_timeout=5000 \
--data retries=3
# 订单服务
curl -i -X POST http://localhost:8001/services \
--data name=order-service \
--data url=http://order-service:8083 \
--data connect_timeout=5000 \
--data write_timeout=10000 \
--data read_timeout=10000
# ====== 2. 创建路由规则 ======
# 用户服务路由
curl -i -X POST http://localhost:8001/services/user-service/routes \
--data name=user-route \
--data paths[]=/api/user \
--data methods[]=GET,POST,PUT,DELETE \
--data strip_path=true
# 订单服务路由
curl -i -X POST http://localhost:8001/services/order-service/routes \
--data name=order-route \
--data paths[]=/api/order \
--data methods[]=POST,GET \
--data strip_path=true
# ====== 3. 启用 JWT 认证插件 ======
curl -i -X POST http://localhost:8001/plugins \
--name jwt \
--config.secret_is_base64=false \
--config.key_claim_name=iss \
--config.claims_to_verify=exp,nbf
# ====== 4. 启用限流插件 ======
curl -i -X POST http://localhost:8001/plugins \
--name rate-limiting \
--config.minute=100 \
--config.policy=local \
--config.limit_by=consumer,ip \
--config.error_code=429 \
--config.error_message='{"error":"Rate limit exceeded"}'使用 Declarative Configuration (YAML)
yaml
# kong.yaml - 声明式配置文件
_format_version: "3.0"
_info:
defaults: true
select_tags:
- production
services:
# 用户服务
- name: user-service
url: http://user-service.default.svc.cluster.local:8081
routes:
- name: user-api
paths:
- /api/user
methods:
- GET
- POST
- PUT
strip_path: true
plugins:
- name: cors
config:
origins:
- "*"
methods:
- GET
- POST
- PUT
- DELETE
- OPTIONS
headers:
- Accept
- Authorization
- Content-Type
exposed_headers:
- X-Request-ID
credentials: true
max_age: 3600
# 订单服务
- name: order-service
url: http://order-service.default.svc.cluster.local:8083
routes:
- name: order-api
paths:
- /api/order
strip_path: true
plugins:
- name: key-auth
- name: rate-limiting
config:
minute: 50
policy: redis
redis_host: redis.default.svc.cluster.local
redis_port: 6379
redis_password: ${REDIS_PASSWORD}
limit_by: consumer
error_code: 429
error_message: '{"error":"Too many requests"}'
- name: request-transformer
config:
add:
headers:
- X-Gateway-Version:3.7.0
- X-Request-Time:${request.timestamp}
plugins:
# 全局 JWT 认证
- name: jwt
enabled: true
protocols:
- https
config:
secret_is_base64: false
claims_to_verify:
- exp
- nbf
key_claim_name: iss
# 全局 CORS
- name: cors
enabled: true
config:
origins:
- "https://app.example.com"
- "https://admin.example.com"
methods:
- GET
- POST
- PUT
- DELETE
- OPTIONS
max_age: 3600
consumers:
- username: mobile-app
plugins:
- name: key-auth
config:
key: ${MOBILE_API_KEY}
- name: acl
config:
groups:
- mobile
- name: rate-limiting
config:
minute: 200
- username: web-admin
plugins:
- name: key-auth
config:
key: ${ADMIN_API_KEY}
- name: acl
config:
groups:
- admin
- name: rate-limiting
config:
minute: 1000
upstreams:
- name: user-service-upstream
algorithm: least-connections
healthchecks:
active:
type: http
http_path: /health
healthy:
interval: 10
successes: 3
unhealthy:
interval: 5
http_failures: 3
targets:
- target: user-service-0.user-service:8081
weight: 100
- target: user-service-1.user-service:8081
weight: 100四、Apache APISIX 实践
4.1 简介
Apache APISIX 是 Apache 基金会的顶级动态 API 网关,由支宝(现网易数帆)开源。2024 年发布了 APISIX 3.9 版本。
4.2 核心优势
- 纯动态:所有配置通过 Admin API 动态生效,无需 Reload
- etcd 驱动:使用 etcd 作为配置中心,天然支持高可用
- 热加载插件:运行时添加/删除/修改插件
- 丰富的路由匹配:支持 URI、Header、Query、Cookie、权重等多维匹配
4.3 Kubernetes 部署
bash
# 安装 APISIX (Helm)
helm repo add apisix https://charts.apisix.io/
helm repo update
helm install apisix apisix/apisix \
--namespace apisix \
--create-namespace \
--set dashboard.enabled=true \
--set ingress-controller.enabled=true \
--set etcd.enabled=true \
--set etcd.replicaCount=3 \
--set gateway.type=LoadBalancer \
--set gateway.http.enabled=true \
--set admin.credentials.admin=${APISIX_ADMIN_KEY} \
--set admin.credentials.viewer=${APISIX_VIEWER_KEY}4.4 路由配置示例
yaml
# apisix-routes.yaml - APISIX 路由配置
apiVersion: apisix.apache.org/v2
kind: ApisixRoute
metadata:
name: ecommerce-routes
namespace: default
spec:
http:
# 用户服务路由
- name: user-service-route
match:
hosts:
- api.example.com
paths:
- /api/user/*
methods:
- GET
- POST
backends:
- serviceName: user-service
servicePort: 8081
plugins:
- name: jwt-auth
enable: true
config:
key: user-jwt-secret
- name: limit-count
enable: true
config:
count: 100
time_window: 60
rejected_code: 429
key_type: var_combination
key: remote_addr + consumer_name
# 订单服务路由 - 金丝雀发布
- name: order-service-canary
match:
hosts:
- api.example.com
paths:
- /api/order/*
backends:
- serviceName: order-service-v1
servicePort: 8083
weight: 90
- serviceName: order-service-v2
servicePort: 8083
weight: 10
plugins:
- name: canary
enable: true
config:
variables:
- canary-version: v2
- name: proxy-rewrite
enable: true
config:
regex_uri: ["^/api/order/(.*)", "/$1"]
# 支付服务路由 - 需要 mTLS
- name: payment-service-route
match:
hosts:
- internal.example.com
paths:
- /api/payment/*
backends:
- serviceName: payment-service
servicePort: 8084
plugins:
- name: client-control-mtls
enable: true
config:
ca: |
-----BEGIN CERTIFICATE-----
...CA证书...
-----END CERTIFICATE-----五、Envoy Gateway — 云原生网关的未来
5.1 简介
Envoy Gateway 是 CNCF 的新项目(v1.1 于 2024 发布),旨在提供符合 Gateway API 规范的 Kubernetes 原生网关体验。
5.2 与 Kong/APISIX 的关键区别
| 维度 | Kong / APISIX | Envoy Gateway |
|---|---|---|
| 配置模型 | 自定义 REST API / etcd | Kubernetes Gateway API CRD |
| 数据面 | Nginx (C) | Envoy (C++) |
| K8s 集成 | 通过 Ingress Controller | 原生 GatewayClass |
| 扩展方式 | Lua/Rust 插件 | Envoy Filter (Wasm) |
| 多集群 | 需额外配置 | 原生 Multi-cluster 支持 |
| 未来方向 | 成熟稳定 | Kubernetes 标准方向 |
5.3 部署示例
bash
# 安装 Envoy Gateway
helm install eg oci://docker.io/envoyproxy/gateway-helm \
--version v1.1.0 \
--namespace envoy-gateway-system \
--create-namespace
# 安装 Gateway API CRDs (如果尚未安装)
kubectl apply -f https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.1.0/standard-install.yamlyaml
# envoy-gateway-config.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: GatewayClass
metadata:
name: envoy-gateway-class
spec:
controllerName: gateway.envoyproxy.io/gatewayclass-controller
---
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
name: ecommerce-gateway
namespace: default
spec:
gatewayClassName: envoy-gateway-class
listeners:
- name: http
protocol: HTTP
port: 80
hostname: "*.example.com"
allowedRoutes:
namespaces:
from: All
- name: https
protocol: HTTPS
port: 443
hostname: "api.example.com"
tls:
mode: Terminate
certificateRefs:
- name: api-tls-secret
---
apiVersion: gateway.networking.k8s.io/v1beta1
kind: HTTPRoute
metadata:
name: api-routes
namespace: default
spec:
parentRefs:
- name: ecommerce-gateway
sectionName: https
hostnames:
- "api.example.com"
rules:
# 用户服务路由
- matches:
- path:
type: PathPrefix
value: /api/user
backendRefs:
- name: user-service
port: 8081
weight: 100
filters:
- type: RequestHeaderModifier
requestHeaderModifier:
set:
- name: X-Source
value: "envoy-gateway"
# 订单服务路由 - 带限流
- matches:
- path:
type: PathPrefix
value: /api/order
backendRefs:
- name: order-service
port: 8083
extensions:
filters:
- type: RateLimitFilter
rateLimitFilter:
unit: Minute
requests: 100六、网关模式 vs Sidecar vs Service Mesh
6.1 三种模式的定位对比
图表渲染中…
6.2 如何选择
| 场景 | 推荐方案 | 原因 |
|---|---|---|
| 统一 API 入口 | API Gateway (Kong/APISIX) | 统一认证、限流、监控 |
| 内部服务间通信 | Service Mesh 或 Sidecar | 更细粒度的流量治理 |
| 南北向流量(入站) | API Gateway + Ingress | 边界安全、SSL 终结 |
| 东西向流量(服务间) | Service Mesh | mTLS、可观测性 |
| 小型团队/快速起步 | Traefik / Nginx | 配置简单,学习成本低 |
| Kubernetes 原生优先 | Envoy Gateway / APISIX | 符合 Gateway API 标准 |
6.3 推荐组合架构
图表渲染中…
七、性能基准测试
7.1 测试环境
- 服务器: AWS c5.2xlarge (8 vCPU, 16GB RAM)
- 测试工具: wrk / hey
- 测试方法: 4 线程, 100 连接, 持续 60 秒
- 后端: 直接返回 200 OK (模拟无计算)
7.2 性能数据
| 网关 | QPS (平均) | P50 延迟 | P99 延迟 | 错误率 | 内存占用 |
|---|---|---|---|---|---|
| Nginx (裸) | 245,000 | 0.12ms | 0.45ms | 0% | ~25MB |
| Kong 3.7 (无插件) | 82,000 | 0.45ms | 2.1ms | 0% | ~120MB |
| Kong 3.7 (5个插件) | 65,000 | 0.58ms | 2.8ms | 0% | ~135MB |
| APISIX 3.9 (无插件) | 105,000 | 0.38ms | 1.6ms | 0% | ~95MB |
| APISIX 3.9 (5个插件) | 88,000 | 0.42ms | 2.0ms | 0% | ~110MB |
| Envoy Gateway v1.1 | 152,000 | 0.28ms | 1.2ms | 0% | ~80MB |
| Traefik v3 | 68,000 | 0.52ms | 3.2ms | 0% | ~85MB |
| Tyk (Go) | 45,000 | 0.78ms | 4.5ms | 0% | ~70MB |
数据来源:各项目官方 Wiki 及社区基准测试报告
7.3 性能优化建议
- 启用 Worker 进程: 设置
worker_processes auto匹配 CPU 核心数 - 调整连接池:
keepalive连接复用减少 TCP 握手开销 - 禁用不必要的日志: 生产环境关闭 access_log 或异步写入
- 启用 HTTP/2: 减少连接数,提升并发能力
- 使用共享内存缓存: JWT 验证结果等可缓存的中间数据
- Lua 代码优化: 避免在请求路径上执行 I/O 密集操作
八、2026 最佳实践总结
8.1 选型决策树
图表渲染中…
8.2 生产环境 Checklist
- 高可用部署:至少 3 个网关节点 + L4 负载均衡器
- SSL/TLS 正确配置:使用 Let's Encrypt 自动证书续期
- 认证授权:统一身份认证(OAuth2/OIDC/JWT)
- 速率限制:按消费者/IP/维度设置合理阈值
- 日志规范:结构化 JSON 日志,包含 trace-id/request-id
- 监控告警:QPS、延迟(P99)、错误率、网关节点健康
- 优雅重启:支持 zero-downtime 配置更新和版本升级
- 安全加固:隐藏版本号、限制 Admin API 访问、定期审计
- 容量规划:根据峰值 QPS 预留 2-3 倍余量
- 灾备方案:跨可用区部署 + 自动故障转移
九、延伸资源
官方文档
- Kong: https://docs.konghq.com/gateway/latest/
- Apache APISIX: https://apisix.apache.org/docs/
- Envoy Gateway: https://gateway.envoyproxy.io/
- Gateway API (K8s SIG): https://gateway-api.sigs.k8s.io/
经典文章
- "Pattern: API Gateway / Backend for Frontend" (Martin Fowler): https://martinfowler.com/articles/bff.html
- "Building Microservices: Using an API Gateway" (Chris Richardson): https://microservices.io/patterns/apigateway.html
- "The API Gateway Pattern" (Microsoft Azure): https://learn.microsoft.com/en-us/azure/architecture/patterns/gateway
开源项目
- Kong: 最流行的 API 网关
- Apache APISIX: Apache 顶级项目
- Envoy Gateway: CNCF 新星
- KrakenD: 高性能 API 聚合网关
- Traefik: 云原生反向代理
本文版本:2026 重制版 | 基于本文档第56篇原文重构 最后更新:2026-06-06 | 技术栈:Kong 3.7 / APISIX 3.9 / Envoy Gateway v1.1 / Kubernetes Gateway API v1.1